#include "client.h"

// 构造函数，初始化服务器 IP 和端口
TCPClient::TCPClient(const string &ip, int port):server_ip(ip),port(port), client_fd(-1){}

// 析构函数，关闭客户端连接以释放资源
TCPClient::~TCPClient()
{
    if(client_fd != -1)
    {
        close(client_fd);
    }
}

// 连接服务器
bool TCPClient::connectToServer()
{
    client_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(client_fd == -1)
    {
        cerr << "Failed to create socket" << endl;
        return false;
    }
    // 配置服务器地址结构
    sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    int byte = inet_pton(AF_INET, server_ip.c_str(), &server_addr.sin_addr);
    if(byte <= 0)
    {
        cerr << "Failed to convert IP address" << endl;
        close(client_fd);
        return false;
    }

    // 连接服务器
    if(connect(client_fd, (sockaddr*)&server_addr, sizeof(server_addr)) == -1)
    {
        cerr << "Failed to connect to server" << endl;
        close(client_fd);
        return false;
    }
    cout << "Connected to server" << endl;
    return true;
}

// 断开连接
void TCPClient::disconnect()
{
    if(client_fd != -1)
    {
        close(client_fd);
        client_fd = -1;
    }
}

// 接收服务器发送的数据
bool TCPClient::receiveData(string &data)
{
    if (client_fd == -1)
    {
        cerr << "Client not connected" << endl;
        return false;
    }
    char buffer[1024];
    int byte = recv(client_fd, buffer, sizeof(buffer), 0);
    if (byte == -1)
    {
        cerr << "Failed to receive data" << endl;
        return false;
    }
    return true;
}

// 向服务器发送数据
bool TCPClient::sendData(const string &data)
{
    if (client_fd == -1)
    {
        cerr << "Client not connected" << endl;
        return false;
    }
    // 发送数据
    int byte = send(client_fd, data.c_str(), data.size(), 0);
    if (byte == -1)
    {
        cerr << "Failed to send data" << endl;
        return false;
    }
    return true;
}

// 重载 << 操作符，向服务器发送数据
TCPClient &TCPClient::operator<<(const string &data)
{
    sendData(data);
    return *this;
}

// 重载 >> 操作符，从服务器接收数据
TCPClient &TCPClient::operator>>(string &data)
{
    receiveData(data);
    return *this;
}

// 关闭客户端连接
void TCPClient::closeclient()
{
    if(client_fd != -1)
    {
        close(client_fd);
        client_fd = -1;
    }
}